package com.wjl.shop.controller;

import com.wjl.shop.entity.SumOrder;
import com.wjl.shop.service.SumOrderService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 汇总表信息(SumOrder)表控制层
 *
 * @author makejava
 * @since 2021-10-07 14:07:23
 */
@RestController
@RequestMapping("sumOrder")
@CrossOrigin
public class SumOrderController {
    /**
     * 服务对象
     */
    @Resource
    private SumOrderService sumOrderService;

    @GetMapping("querySum")
    public Map<String,Object> querySum(SumOrder sumOrder,
                                       @RequestParam(name = "currentPage",defaultValue = "1") Integer currentPage,
                                       @RequestParam(name = "pages",defaultValue = "10")Integer pages){
        return sumOrderService.queryAllBySumOrder(sumOrder,currentPage,pages);
    }

    @PostMapping("save")
    public Map<String,Object> save(@RequestBody List<SumOrder> sumOrders){
        try {
            final Map<String, Object> insert = sumOrderService.insert(sumOrders);
            return insert;
        }catch (Exception e){
            final HashMap<String, Object> map = new HashMap<>();
            map.put("status","fail");
            map.put("message","汇总失败.");
            map.put("data",e.toString());
            return map;
        }
    }

    @RequestMapping("export")
    public void export(@RequestParam(value = "ids") List<Integer> ids, HttpServletResponse response){
        if(ids.size()>0){
            try {
                final HSSFWorkbook hssfWorkbook = sumOrderService.exportSumOrder(ids);
                final ServletOutputStream outputStream = response.getOutputStream();
                response.reset();
                response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
                response.setHeader("Content-disposition", "attachment; filename=export.xls");
                response.setContentType("application/msexcel");
                hssfWorkbook.write(outputStream);
                outputStream.flush();
                outputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @GetMapping("detail")
    public SumOrder detail(Integer id){
        return sumOrderService.queryById(id);
    }


}
